package com.mifengkong.frtools.http.cookie;


import android.text.TextUtils;

import com.mifengkong.frtools.http.util.CookieConstant;
import com.mifengkong.frtools.util.FRSharedPreferences;

import java.io.IOException;
import java.util.HashSet;

import okhttp3.Interceptor;
import okhttp3.Response;

/**
 * @author jiangyongxing
 * @date 2017/9/12
 * 描述：
 */

public class SaveCookiesInterceptor implements Interceptor {

    private String[] loginUrls = new String[]{};

    public SaveCookiesInterceptor(String... loginUrls) {
        this.loginUrls = loginUrls;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        Response originalResponse = chain.proceed(chain.request());
        for (String loginUrl : loginUrls) {
            if (!TextUtils.isEmpty(loginUrl) && chain.request().url().toString().contains(loginUrl)) {
                //当前链接需要保存cookie
                if (originalResponse.headers("Set-Cookie").isEmpty()) {
                    break;
                }
                //当前的链接有cookie值
                HashSet<String> cookies = new HashSet<>();
                for (String header : originalResponse.headers("Set-Cookie")) {
                    cookies.add(header);
                }
                FRSharedPreferences.setStringSet(CookieConstant.SP_NAME_COOKIES, CookieConstant.PREF_COOKIES, cookies);
                break;
            }
        }

        return originalResponse;
    }
}
